package com.gla.market.fragments;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.activity.OrderActivity;
import com.gla.market.adapter.ShopListAdapter;
import com.gla.market.adapter.ShoppingCartAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.ShopCart;
import com.gla.market.entity.ShopInCart;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;

import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Shopcart extends Fragment {

    private Context mContext;
    private CheckBox ckAll;//全选框
    private TextView priceTextView; //总额
    private TextView numberTextView; //数量
    private RecyclerView shopListView;//店铺列表
    private Button submitButton;    //提交按钮
    private ProgressBar loadding;   //加载中图标
    private SwipeRefreshLayout swipeRefreshLayout;//下拉刷新控件
    private ShopCartReceiver shopCartReceiver;
    private IntentFilter intentFilter;
    private long lastTime;//解决异常bug，限制点击一次数量变多次的问题

    //商品列表adapter
    private ShoppingCartAdapter shoppingCartAdapter;
    //店铺列表adapter
    private ShopListAdapter shopListAdapter;

    //购物车商品列表
    public List<ShopCart> shoppingCartBeanList = new ArrayList<>();
    //商店列表
    private ArrayList<ShopInCart> shopBeanList = new ArrayList<>();

    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private Integer user_id;//user_id

    public static String CHECK = "com.gla.market.CHECK";
    public static String ADD = "com.gla.market.ADD";
    public static String REDUCE = "com.gla.market.REDUCE";
    public static String DELETE = "com.gla.market.DELETE";
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getContext();
        View view = inflater.inflate(R.layout.fragment_shopcart, null);
        init(view);
        super.onCreate(savedInstanceState);
        //从SharedPreferences中获取用户id
        user_id = (Integer) SharedPreferencesUtil.get(mContext, "userInfo", "user_id", -1);
        //广播接收器
        intentFilter = new IntentFilter();
        intentFilter.addAction(CHECK);
        intentFilter.addAction(ADD);
        intentFilter.addAction(REDUCE);
        intentFilter.addAction(DELETE);
        shopCartReceiver = new ShopCartReceiver();
        mContext.registerReceiver(shopCartReceiver,intentFilter);

        //初始化绑定控件
        init(view);
        //初始化数据
        initData();
        return view;
    }

    @Override
    public void onResume(){
        super.onResume();

        //订单结束后清除选择状态
        for(int i=0;i<shopBeanList.size();i++){
            shopBeanList.get(i).setChoosed(false);
            updateShopHead(i);
            for(int j=0;j<shopBeanList.get(i).getList().size();j++){
                shopBeanList.get(i).getList().get(j).setChoosed(false);
            }
            updateShopItem(i);
        }
        ckAll.setChecked(false);
    }

    private void init(View view){

        swipeRefreshLayout = view.findViewById(R.id.refresh_layout);
        shoppingCartAdapter = new ShoppingCartAdapter(mContext);
        shopListAdapter = new ShopListAdapter(mContext);
        loadding = view.findViewById(R.id.shopcart_loadding);
        shopListView = view.findViewById(R.id.shopcart_content);
        shopListView.addItemDecoration(new SpaceItemDecoration(20));//设置item间距
        shopListView.setLayoutManager(new LinearLayoutManager(mContext));
        numberTextView = view.findViewById(R.id.shopcart_number);
        priceTextView = view.findViewById(R.id.shopcart_money);
        ckAll = view.findViewById(R.id.shopcart_checkall);
        submitButton = view.findViewById(R.id.shopcart_submit);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay();
            }
        });
        //全选监听器
        ckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(shopBeanList.size() != 0){
                    if (ckAll.isChecked()) {
                        for(int i=0;i<shopBeanList.size();i++){
                            List<ShopCart> list = shopBeanList.get(i).getList();
                            for(int j=0;j<list.size();j++){
                                list.get(j).setChoosed(true);
                            }
                            shopBeanList.get(i).setChoosed(true);
                            updateShopItem(i);
                            updateShopHead(i);
                        }
                    } else {
                        for(int i=0;i<shopBeanList.size();i++){
                            List<ShopCart> list = shopBeanList.get(i).getList();
                            for(int j=0;j<list.size();j++){
                                list.get(j).setChoosed(false);
                            }
                            shopBeanList.get(i).setChoosed(false);
                            updateShopItem(i);
                            updateShopHead(i);
                        }
                    }
                }
                statistics();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
    }

    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //定义一个弹出层dialog
            AlertDialog alert = new AlertDialog.Builder(mContext).create();
            int shopcart_id;
            int commodity_id;
            switch (msg.what) {
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "未登录！获取购物车商品数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    ckAll.setChecked(false);
                    priceTextView.setText("￥0.00");
                    //设置顶部数量
                    numberTextView.setText("("+totalCount+")");
                    //隐藏加载中
                    loadding.setVisibility(View.GONE);
                    shopListView.setAdapter(shopListAdapter);
                    shopListAdapter.setshopBeanList(shopBeanList);
                    break;
                case 2:
                    //购买结算
                    alert.setTitle("提示");
                    alert.setMessage(msg.obj == null ? "购买请求处理失败！"
                            : msg.obj.toString());
                    alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(mContext, "提交成功!", Toast.LENGTH_SHORT).show();
                                }
                            });
                    alert.show();
                    break;
                case 3:
                    shopcart_id = (int)msg.obj;
                    for (int i = 0; i < shopBeanList.size(); i++) {
                        List<ShopCart> list = shopBeanList.get(i).getList();
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getId() == shopcart_id) {
                                list.remove(j);
                                shopListAdapter.setshopBeanList(shopBeanList);
                                //自定义局部刷新
                                updateShopItem(i);
                            }
                        }
                    }
                    //RecyclerView中remove掉item
                    statistics();
                    //删除商品
                    Toast.makeText(mContext, "删除成功!", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(mContext, msg.obj == null ? "刷新购物车数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    //更新试图
                    statistics();
                    shoppingCartAdapter.notifyDataSetChanged();
                    //删除商品
                    Toast.makeText(mContext, "购买成功!", Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    shopcart_id = (int)msg.obj;
                    Log.d("ID", ""+shopcart_id);
                    for (int i = 0; i < shopBeanList.size(); i++) {
                        List<ShopCart> list = shopBeanList.get(i).getList();
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getId() == shopcart_id) {
                                if(list.get(j).getNumber() > 1){
                                    list.get(j).setNumber(list.get(j).getNumber()-1); //数量+1
                                    //自定义局部刷新
                                    updateShopItem(i);
                                    Log.d("调试","减少成功"+list.get(j));
                                }
                            }
                        }
                    }
                    statistics();
                    break;
                case 7:
                    commodity_id = (int)msg.obj;
                    Log.d("ID", ""+commodity_id);
                    for (int i = 0; i < shopBeanList.size(); i++) {
                        List<ShopCart> list = shopBeanList.get(i).getList();
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getId() == commodity_id) {
                                list.get(j).setNumber(list.get(j).getNumber() + 1); //数量+1
                                //自定义局部刷新
                                updateShopItem(i);
                                Log.d("调试","增加成功"+list.get(j));
                            }
                        }
                    }
                    statistics();
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (swipeRefreshLayout.isRefreshing()) {
                //停止动画
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    };

    /**
     * 从网络获取购物车数据
     */
    protected void initData() {
        //拼接url
        String url = Constants.BASE_URL + Constants.GET_QUERY_CART_URL + "?user_id=" + user_id;

        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println("获取购物"+object);
                if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                    shopBeanList.clear();
                    message.what = 1;
                    //解析拿到data中的lists数据
                    JSONArray lists = ((JSONArray) object.get("data"));
                    //Log.d("调试","获取商品数据:"+lists);
                    //将list传递给数据集
                    shoppingCartBeanList = JSONArray.parseArray(JSON.toJSONString(lists), ShopCart.class);
                    totalCount = shoppingCartBeanList.size();
                    for (int i=0;i<shoppingCartBeanList.size();i++){
                        ShopCart item = shoppingCartBeanList.get(i);
                        boolean exist = false;//标记商店是否已存在
                        for(int j=0;j<shopBeanList.size();j++){
                            if(shopBeanList.get(j).getId().equals(item.getCommodity().getShop().getId())){
                                exist = true;
                                shopBeanList.get(j).getList().add(item);//加入商店item
                                shoppingCartBeanList.remove(item);
                                i--;
                                break;
                            }
                        }
                        if(!exist){
                            //向店铺卡片添加商品
                            ShopInCart shopItem = new ShopInCart();
                            shopItem.setId(item.getCommodity().getShop().getId());
                            shopItem.getList().add(item);
                            shopBeanList.add(shopItem);
                            shopItem.setName(item.getCommodity().getShop().getName());
                        }
                    }
                } else {
                    message.what = 0;
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    /**
     * 结算订单、支付
     */
    private void pay() {
        ArrayList<ShopInCart> list = new ArrayList<>();
        for (int i=0;i<shopBeanList.size();i++){
            for(int j=0;j<shopBeanList.get(i).getList().size();j++){
                ShopCart item = shopBeanList.get(i).getList().get(j);
                if(item.getChoosed()) {
                    boolean exist = false;//标记商店是否已存在
                    for(int k=0;k<list.size();k++){
                        if(list.get(k).getId().equals(item.getCommodity().getShop().getId())){
                            exist = true;
                            list.get(k).getList().add(item);//加入商店item
                            break;
                        }
                    }
                    if(!exist){
                        //向店铺卡片添加商品
                        ShopInCart shopItem = new ShopInCart();
                        shopItem.setId(item.getCommodity().getShop().getId());
                        shopItem.getList().add(item);
                        shopItem.setName(item.getCommodity().getShop().getName());
                        list.add(shopItem);
                    }
                }
            }
        }
        if(list.size()!=0){
            Intent intent = new Intent(mContext, OrderActivity.class);
            //把用户选择的商品传给订单页面
            intent.putExtra("list", list);
            startActivity(intent);
        } else {
            Toast.makeText(mContext,"还未选择商品哦~",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 修改商店按钮、全选按钮
     *
     * @return
     */
    private void updateCheck() {

        boolean allChecked = true;
        for(int i=0;i<shopBeanList.size();i++){
            List<ShopCart> list = shopBeanList.get(i).getList();
            boolean allChecked2 = true;
            //遍历该商店所有商品
            for(int j=0;j<list.size();j++){
                if(list.get(j).getChoosed()==false){
                    allChecked2 = false;
                }
            }
            shopBeanList.get(i).setChoosed(allChecked2);
            updateShopHead(i);
        }
        for(int i=0;i<shopBeanList.size();i++){
            if(shopBeanList.get(i).getChoosed()==false){
                allChecked = false;
            }
        }
        ckAll.setChecked(allChecked);

    }

    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;

        for(int i=0;i<shopBeanList.size();i++){
            List<ShopCart> list = shopBeanList.get(i).getList();
            for(int j=0;j<list.size();j++){
                if(list.get(j).getChoosed()){
                    totalCount++;
                    totalPrice += list.get(j).getCommodity().getPrice() * list.get(j).getNumber();
                }
            }
        }
        //保留两位小数
        DecimalFormat df = new DecimalFormat("0.00");
        String str = df.format(totalPrice);
        priceTextView.setText("￥" + str);
    }

    /**
     * 增加
     *
     * @param shoppingcar_id 购物车item id
     */
    public void doIncrease(Integer shoppingcar_id) {
        Integer commodity_id=-1;
        for(ShopCart item : shoppingCartBeanList){
            if(item.getId() == shoppingcar_id) {
                commodity_id = item.getCommodity().getId();
            }
        }
        String url = Constants.BASE_URL + Constants.GET_ADD_SHOPPINGCART_URL + "?commodity_id="+commodity_id+"&user_id="+user_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {

                    message.what = 7;
                    message.obj = shoppingcar_id;

                } else {
                    Log.d("调试","增加失败:"+object.getString("message"));
                    message.what = 0;
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    /**
     * 删减
     *
     * @param shopcart_id 购物车item id
     */
    public void doDecrease(Integer shopcart_id) {
        String url = Constants.BASE_URL + Constants.GET_REDUCE_SHOPPINGCART_URL + "?id="+shopcart_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    Log.d("调试","减少成功");
                    message.what = 6;
                    message.obj = shopcart_id;

                } else {
                    Log.d("调试","减少失败:"+object.getString("message"));
                    message.what = 0;
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    /**
     * 删除
     *
     * @param shopcart_id
     */
    public void doDelete(Integer shopcart_id) {
        //向服务器发送删除请求
        String url = Constants.BASE_URL + Constants.POST_DELETE_URL + "?id="+shopcart_id;
        Log.d("调试","删除请求"+url);
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Log.d("调试",result);
                Message message = Message.obtain();
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    Log.d("调试","删除成功");
                    message.what = 3;
                    message.obj = shopcart_id;

                } else {
                    Log.d("调试","删除失败");
                    message.what = 0;
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    //广播接收器
    class ShopCartReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            long time = System.currentTimeMillis();
            if(time-lastTime < 500) {
                return;
            }
            //更新选择
            if(intent.getAction().equals(CHECK)) {
                Integer shopcart_id = intent.getIntExtra("shopcart_id", -1);
                Boolean checked = intent.getBooleanExtra("checked", false);

                for (int i = 0; i < shopBeanList.size(); i++) {
                    List<ShopCart> list = shopBeanList.get(i).getList();
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(j).getId() == shopcart_id) {
                            list.get(j).setChoosed(checked);
                            //shopListAdapter.notifyItemChanged(i);
                            //自定义局部刷新
                            updateShopItem(i);
                        }
                    }
                }
                //更新视图
                updateCheck();
                //更新价格
                statistics();
            } else if(intent.getAction().equals(ADD)){  //增加数量
                Log.d("调试","监听到+1");
                Integer shopcart_id = intent.getIntExtra("shopcart_id", -1);
                doIncrease(shopcart_id);

            } else if(intent.getAction().equals(REDUCE)){   //减少数量
                Log.d("调试","监听到-1");
                Integer shopcart_id = intent.getIntExtra("shopcart_id", -1);
                doDecrease(shopcart_id);

            }  else if(intent.getAction().equals(DELETE)){  //删除商品
                Integer shopcart_id = intent.getIntExtra("shopcart_id", -1);
                doDelete(shopcart_id);

            }

            //重新计算金额
            statistics();
            lastTime = time;
        }
    }

    //修改RecyclerView Item间隔的辅助类
    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mSpace;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = mSpace/2;
            }
            outRect.left = outRect.right = 12;
        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }

    /**
     * 局部更新店铺里的商品列表
     * @param position
     */
    public void updateShopItem(int position){
        View v = shopListView.getLayoutManager().findViewByPosition(position);
        if(v != null){
            RecyclerView v2 = v.findViewById(R.id.shopcart_shop_content);
            if(v2 != null){
                v2.getAdapter().notifyDataSetChanged();
            }
        }

    }

    /**
     * 局部更新店铺的选择框
     * @param position
     */
    public void updateShopHead(int position){
        View v = shopListView.getLayoutManager().findViewByPosition(position);
        if(v!=null){
            CheckBox check = v.findViewById(R.id.ck_shopcart_chose);
            if(check!=null){
                check.setChecked(shopBeanList.get(position).getChoosed());
            }
        }
    }
}